//package com.lh.core;
//
//import cn.hutool.core.collection.CollectionUtil;
//import cn.hutool.core.util.ObjectUtil;
//import cn.hutool.core.util.StrUtil;
//import com.lh.entity.activiti.FindPersonalTask;
//import com.lh.utils.LogUtil;
//import org.activiti.engine.*;
//import org.activiti.engine.repository.Deployment;
//import org.activiti.engine.repository.DeploymentQuery;
//import org.activiti.engine.runtime.ProcessInstance;
//import org.activiti.engine.task.Task;
//import org.activiti.engine.task.TaskQuery;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//import java.util.*;
//
///**
// * activiti流程服务集合
// */
//@Component
//public class ActivitiProcessCore {
//
//    LogUtil LOG = new LogUtil(ActivitiProcessCore.class);
//
//    @Autowired
//    private TaskService taskService;
//
//    @Autowired
//    private RuntimeService runtimeService;
//
//    @Autowired
//    private RepositoryService repositoryService;
//
//
//    /**
//     * 流程部署
//     *
//     * @param deploymentName 流程部署名称
//     * @param path           dpmn路径
//     */
//    public void deployment(String deploymentName, String path) {
//        DeploymentQuery deploymentQuery = repositoryService.createDeploymentQuery().deploymentName(deploymentName);
//        List<Deployment> deploymentList = deploymentQuery.list();
////        if (CollectionUtil.isEmpty(deploymentList)) {
//        //使用service进行流程的部署，定义一个流程的名字，把bpmn和png部署到数据中
//        Deployment deploy = repositoryService.createDeployment()
//                .name(deploymentName)
//                .addClasspathResource(path)
//                .deploy();
//        LOG.info("创建流程部署id=" + deploy.getId());
//        LOG.info("创建流程部署key=" + deploy.getKey());
//        LOG.info("创建流程部署名字=" + deploy.getName());
////        }
//    }
//
//    /**
//     * 删除流程部署
//     *
//     * @param id 流程部署Deploymentid
//     */
//    public void deleteDeployment(String id) {
//        //通过部署id来删除流程部署信息
//        repositoryService.deleteDeployment(id, true);
//    }
//
//    /**
//     * 启动流程实例
//     * `act_hi_actinst`      流程实例执行历史信息
//     * `act_hi_identitylink` 流程参与用户的历史信息
//     * `act_hi_procinst`     流程实例的历史信息
//     * `act_hi_taskinst`     流程任务的历史信息
//     * `act_ru_execution`    流程执行信息
//     * `act_ru_identitylink` 流程的正在参与用户信息
//     * `act_ru_task`         流程当前任务信息
//     * 注：默认启动版本最高的流程定义
//     * @param businessKey      电梯业务id
//     * @param nextAssigneeMap  下一环节参数
//     */
//    public boolean startProcess(String businessKey, Map<String,Object> nextAssigneeMap) {
//        try {
//            ProcessInstance instance = runtimeService.startProcessInstanceByKey("zfjsNew", businessKey, nextAssigneeMap);
//            LOG.info("已完成《" + instance.getId() + "》已启动");
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return false;
//        }
////        ProcessInstance instance = runtimeService.startProcessInstanceByKey("lift", businessKey);
////        Map<String, Object> nextAssigneeMap1 = new HashMap<>();
////        nextAssigneeMap1.put("apply","hahah");
////        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
////        RuntimeService runtimeService = processEngine.getRuntimeService();
////        ProcessInstance processInstance = runtimeService.
////                startProcessInstanceByKey("demo","1001",nextAssigneeMap1);
////        System.out.println("业务id=="+processInstance.getBusinessKey());
//    }
//
//    /**
//     * 查询个人任务
//     *
//     * @param taskName     流程名称
//     * @param taskAssignee 当前流程人
//     * @param isDueDate    是否限制时间
//     */
//    public FindPersonalTask findPersonalTaskList(String taskName, String taskAssignee, boolean isDueDate) {
//        FindPersonalTask findPersonalTask = new FindPersonalTask();
//        List<String> businessKeyList = CollectionUtil.newArrayList();
//        List<String> taskIdList = CollectionUtil.newArrayList();
//        TaskQuery taskQuery = taskService.createTaskQuery();
//        if (StrUtil.isNotBlank(taskName)) {
//            taskQuery.taskName(taskName);
//        }
//        if (StrUtil.isNotBlank(taskAssignee)) {
//            taskQuery.taskAssignee(taskAssignee);
//        }
//        if (isDueDate) {
//            taskQuery.taskDueAfter(new Date());
//        }
//        List<Task> taskList = taskQuery.list();
//        for (Task task : taskList) {
//            String processInstanceId = task.getProcessInstanceId();
//            taskIdList.add(task.getId());
//            ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
//            if (ObjectUtil.isNotEmpty(instance)) {
//                businessKeyList.add(instance.getBusinessKey());
//            }
//        }
//        findPersonalTask.setTaskIds(taskIdList);
//        findPersonalTask.setBusinessIds(businessKeyList);
//        return findPersonalTask;
//    }
//
//
//    /**
//     * 查询历史流程
//     *
//     * @param businessKey 业务id
//     * @param processInstanceId 流程实例ID
//     * @param assigneeUserId 用户id
//     * @param isEffective    有效节点
//     */
////    public List<SThistoricActivity> queryHistoryProcess(String businessKey, String processInstanceId, String assigneeUserId, Boolean isEffective) {
////        HistoricActivityInstanceQuery historicActivityInstanceQuery = historyService.createHistoricActivityInstanceQuery();
////        List<SThistoricActivity> sThistoricActivities = CollectionUtil.newArrayList();
////        if (StrUtil.isNotBlank(businessKey)) {
////            ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();
////            if (ObjectUtil.isEmpty(instance)) {
////                throw new RuntimeException("未查询到流程实例");
////            }
////            historicActivityInstanceQuery.processInstanceId(instance.getProcessInstanceId());
////        }
////        if (StrUtil.isNotBlank(processInstanceId)) {
////            historicActivityInstanceQuery.processInstanceId(processInstanceId);
////        }
////        if (StrUtil.isNotBlank(assigneeUserId)) {
////            historicActivityInstanceQuery.taskAssignee(assigneeUserId);
////        }
////        List<HistoricActivityInstance> historicActivityInstanceList = historicActivityInstanceQuery
////                .orderByHistoricActivityInstanceStartTime()
////                .asc()
////                .list();
////        if (CollectionUtil.isEmpty(historicActivityInstanceList)) {
////            throw new RuntimeException("未查询到流程信息");
////        }
////
////        historicActivityInstanceList = historicActivityInstanceList.stream().filter(historicActivityInstance -> StrUtil.isNotBlank(historicActivityInstance.getActivityName())).collect(Collectors.toList());
////        List<HistoricActivityInstance> HistoricActivityInstanceEffectiveList = CollectionUtil.newArrayList();
////        List<String> activityNameList = historicActivityInstanceList.stream().map(HistoricActivityInstance::getActivityName).collect(Collectors.toList());
////        List<String> activityEquNameList = activityNameList.stream().filter(i -> activityNameList.stream().filter(i::equals).count() > 1).distinct().collect(Collectors.toList());
////        activityEquNameList = activityEquNameList.stream().filter(activityEquName -> !activityEquName.equals("上传报价")).collect(Collectors.toList());
////        if (CollectionUtil.isEmpty(activityEquNameList)) {
////            isEffective = false;
////        }
////        if (isEffective) {
////            if (activityEquNameList.size() == 1 && activityEquNameList.get(0).equals(activityNameList.get(activityNameList.size() - 1))) {
////                String endActivityName = activityNameList.get(historicActivityInstanceList.size() - activityEquNameList.size());
////                int endIndex = activityNameList.indexOf(endActivityName);
////                for (int i = 0; i < activityNameList.size(); i++) {
////                    if (i < endIndex) {
////                        HistoricActivityInstanceEffectiveList.add(historicActivityInstanceList.get(i));
////                    }
////                }
////                for (int i = 0; i < activityEquNameList.size(); i++) {
////                    HistoricActivityInstanceEffectiveList.add(historicActivityInstanceList.get(activityNameList.lastIndexOf(activityEquNameList.get(i))));
////                }
////
////            } else {
////                for (int i = 0; i < activityNameList.size(); i++) {
////                    if (!activityEquNameList.contains(activityNameList.get(i))) {
////                        HistoricActivityInstanceEffectiveList.add(historicActivityInstanceList.get(i));
////                    }
////                }
////                for (int i = 0; i < activityEquNameList.size(); i++) {
////                    HistoricActivityInstanceEffectiveList.add(historicActivityInstanceList.get(activityNameList.lastIndexOf(activityEquNameList.get(i))));
////                }
////            }
////            sThistoricActivities = BeanUtil.copyToList(HistoricActivityInstanceEffectiveList, SThistoricActivity.class);
////            sThistoricActivities.forEach(historicActivity -> historicActivity.setResult("批准"));
////        } else {
////            sThistoricActivities = BeanUtil.copyToList(historicActivityInstanceList, SThistoricActivity.class);
////            sThistoricActivities.forEach(historicActivity -> historicActivity.setResult("批准"));
////            for (String activityEquName : activityEquNameList) {
////                sThistoricActivities.get(activityNameList.indexOf(activityEquName)).setResult("驳回");
////            }
////        }
////
////        //合并并行流程节点
//////        List<String> activityDistNameList = sThistoricActivities.stream().map(SThistoricActivity::getActivityName).collect(Collectors.toList());
//////        if (activityDistNameList.stream().anyMatch(name -> name.contains("上传报价"))) {
//////            List<SThistoricActivity> mergeList = CollectionUtil.newArrayList();
//////            List<Integer> indexList = CollectionUtil.newArrayList();
//////            for (int i = 0; i < activityDistNameList.size(); i++) {
//////                if (activityDistNameList.get(i).contains("上传报价")) {
//////                    mergeList.add(sThistoricActivities.get(i));
//////                    indexList.add(activityDistNameList.indexOf(activityDistNameList.get(i)));
//////                }
//////            }
//////            boolean endTime = mergeList.stream().map(SThistoricActivity::getEndTime).collect(Collectors.toList()).contains(null);
//////            SThistoricActivity sThistoricActivity = new SThistoricActivity();
//////            sThistoricActivity.setActivityId(StrUtil.join(",", mergeList.stream().map(SThistoricActivity::getActivityId).collect(Collectors.toList())));
//////            sThistoricActivity.setActivityName(StrUtil.join(",", mergeList.stream().map(SThistoricActivity::getActivityName).collect(Collectors.toList())));
//////            sThistoricActivity.setAssignee(StrUtil.join(",", mergeList.stream().map(SThistoricActivity::getAssignee).collect(Collectors.toList())));
//////            sThistoricActivity.setTaskId(StrUtil.join(",", mergeList.stream().map(SThistoricActivity::getTaskId).collect(Collectors.toList())));
//////            sThistoricActivity.setProcessInstanceId(sThistoricActivities.get(indexList.get(0)).getProcessInstanceId());
//////            sThistoricActivity.setStartTime(sThistoricActivities.get(indexList.get(0)).getStartTime());
//////            sThistoricActivity.setEndTime(endTime ? null : sThistoricActivities.get(indexList.get(0)).getEndTime());
//////            sThistoricActivity.setResult("批准");
//////            sThistoricActivities = sThistoricActivities.stream().filter(name -> !name.getActivityName().contains("上传报价")).collect(Collectors.toList());
//////            sThistoricActivities.add(indexList.get(0), sThistoricActivity);
//////        }
////
////        return sThistoricActivities.stream().sorted(Comparator.comparing(SThistoricActivity::getStartTime)).collect(Collectors.toList());
////    }
//
//    /**
//     * 查询历史流程业务号
//     * @param instanceId 实例id
//     */
////    public String queryHistoryBusinessKey(String instanceId) {
////        HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery();
////        HistoricProcessInstance historicProcessInstance = historicProcessInstanceQuery.processInstanceId(instanceId)
////                .singleResult();
////        if (ObjectUtil.isEmpty(historicProcessInstance)){
////            return null;
////        }
////        return historicProcessInstance.getBusinessKey();
////    }
//
//    /**
//     * 查询当前业务环节信息
//     * @param businessKey 业务id
//     */
////    public List<Task> queryTask(String businessKey) {
////        return taskService.createTaskQuery().processInstanceBusinessKey(businessKey).list();
////    }
//
//
//    /**
//     * 查询当前环节评价
//     * @param taskid 当前环节的taskid
//     */
////    public String getTaskComments(String taskid) {
////        List<Comment> taskComments = taskService.getTaskComments(taskid);
////        List<String> messages = taskComments.stream().map(Comment::getFullMessage).collect(Collectors.toList());
////        return StrUtil.join("、", messages);
////    }
//
//    /**
//     * 完成个人任务
//     *
//     * @param businessKey     业务id
//     * @param currentAssignee 当前完成人
//     * @param comment         审批意见
//     * @param nextAssigneeMap 下一环节参数
//     */
//    public boolean completTask(String businessKey, String currentAssignee, String comment, Map<String, Object> nextAssigneeMap) {
//        try{
//            TaskQuery taskQuery = taskService.createTaskQuery();
//            if (StrUtil.isNotBlank(businessKey)) {
//                taskQuery.processInstanceBusinessKey(businessKey);
//            }
//            if (StrUtil.isNotBlank(currentAssignee)) {
//                taskQuery.taskAssignee(currentAssignee);
//            }
//            List<Task> taskList = taskQuery.list();
//            if (CollectionUtil.isNotEmpty(taskList)) {
//                for (Task task : taskList) {
//                    if (StrUtil.isNotBlank(comment)) {
//                        taskService.addComment(task.getId(), task.getProcessInstanceId(), comment);
//                    }
//                    if (CollectionUtil.isNotEmpty(nextAssigneeMap)) {
//                        taskService.complete(task.getId(), nextAssigneeMap);
//                    } else {
//                        taskService.complete(task.getId());
//                    }
//                    LOG.info("已完成《" + task.getAssignee() + "》任务，当前流程：" + task.getName() + "，tackID：" + task.getId());
//                }
//            }
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return false;
//        }
//    }
//
//
//    /**
//     * 结束任务
//     * @param taskId    当前任务ID
//     */
////    public void endTask(String taskId) {
////        //  当前任务
////        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
////
////        BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
////        List<EndEvent> endEventList = bpmnModel.getMainProcess().findFlowElementsOfType(EndEvent.class);
////        FlowNode endFlowNode = endEventList.get(0);
////        FlowNode currentFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(task.getTaskDefinitionKey());
////
////        //  临时保存当前活动的原始方向
////        List<SequenceFlow> originalSequenceFlowList = CollectionUtil.newArrayList();
////        originalSequenceFlowList.addAll(currentFlowNode.getOutgoingFlows());
////        //  清理活动方向
////        currentFlowNode.getOutgoingFlows().clear();
////
////        //  建立新方向
////        SequenceFlow newSequenceFlow = new SequenceFlow();
////        String uuid = UUID.randomUUID().toString().replace("-", "");
////        newSequenceFlow.setId(uuid);
////        newSequenceFlow.setSourceFlowElement(currentFlowNode);
////        newSequenceFlow.setTargetFlowElement(endFlowNode);
////        List<SequenceFlow> newSequenceFlowList = CollectionUtil.newArrayList();
////        newSequenceFlowList.add(newSequenceFlow);
////        //  当前节点指向新的方向
////        currentFlowNode.setOutgoingFlows(newSequenceFlowList);
////
////        //  完成当前任务
////        taskService.complete(task.getId());
////
////        //  可以不用恢复原始方向，不影响其它的流程
//////        currentFlowNode.setOutgoingFlows(originalSequenceFlowList);
////    }
//
//
//
//    /**
//     * 递归遍历获取上个任务节点
//     **/
////    public void getIncomeNodesRecur(String currentNodeId, List<Map<String, String>> incomeNodes, Process process, boolean isAll) {
////        FlowElement currentFlowElement = process.getFlowElement(currentNodeId);
////        List<SequenceFlow> incomingFlows = null;
////        if (currentFlowElement instanceof UserTask) {
////            incomingFlows = ((UserTask) currentFlowElement).getIncomingFlows();
////        } else if (currentFlowElement instanceof Gateway) {
////            incomingFlows = ((Gateway) currentFlowElement).getIncomingFlows();
////        } else if (currentFlowElement instanceof StartEvent) {
////            incomingFlows = ((StartEvent) currentFlowElement).getIncomingFlows();
////        }
////        if (incomingFlows != null && incomingFlows.size() > 0) {
////            incomingFlows.forEach(incomingFlow -> {
////                // 出线的上一节点
////                String sourceFlowElementID = incomingFlow.getSourceRef();
////                // 查询上一节点的信息
////                FlowElement preFlowElement = process.getFlowElement(sourceFlowElementID);
////
////                //用户任务
////                if (preFlowElement instanceof UserTask) {
////                    Map<String, String> tempMap = new HashMap<>();
////                    tempMap.put("id", preFlowElement.getId());
////                    tempMap.put("name", preFlowElement.getName());
////                    incomeNodes.add(tempMap);
////                    if (isAll) {
////                        getIncomeNodesRecur(preFlowElement.getId(), incomeNodes, process, true);
////                    }
////                }
////                //排他网关
////                else if (preFlowElement instanceof ExclusiveGateway) {
////                    getIncomeNodesRecur(preFlowElement.getId(), incomeNodes, process, isAll);
////                }
////                //并行网关
////                else if (preFlowElement instanceof ParallelGateway) {
////                    getIncomeNodesRecur(preFlowElement.getId(), incomeNodes, process, isAll);
////                }
////            });
////        }
////    }
//
//    /**
//     * 拾取组任务
//     * @param taskId 当前任务id
//     * @param userId 用户名
//     */
////    public void claimTask(String taskId,String userId){
////        //拾取任务
////        //即使该用户不是候选人也能拾取(建议拾取时校验是否有资格)
////        //校验该用户有没有拾取任务的资格
////        Task task = taskService.createTaskQuery()
////                .taskId(taskId)
////                //taskCandidateUser(userId)//根据候选人查询
////                .singleResult();
////        if(task!=null){
////            //拾取任务
////            taskService.claim(taskId, userId);
////            LOG.info("任务id:" + taskId + "已被用户"+userId+"拾取成功");
////        }
////    }
//}
